﻿//Call this as:
// <movieClipObject>.delay(<delayInMillis>, <objectOfFunction>, <function, fully qualified>, <arrayOfArgsForFunction>);

//Put on your first frame everything below:

MovieClip.prototype.functionArray;

function setDelay(delay, obj, functionCall, args) {
        var curTime = (new Date()).getTime();
        var timeToCall = curTime+delay;
        if (functionArray == null)
        functionArray = new Array();
        functionArray.push(new Array(timeToCall, obj, functionCall, args));
        functionArray.sort(order);
}

function order (a, b) {
        var name1 = a[0];
        var name2 = b[0];
        if (name1 < name2) {
                return -1;
        } else if (name1 > name2) {
                return 1;
        } else {
                return 0;
        }
}


/**
* Delay Function
* v1 author Lon F. Binder lon@lonbinder.com
*
* delay - Long How long to delay function call (in millis)
* obj - Object The object, on which the function is being called
* functionCall - Function the name of the function to call (fully qualify function names)
* args - Array The array of arguments to pass to function
*/
MovieClip.prototype.delay = function (delay, obj, functionCall, args) {
        trace("setting");
        setDelay(delay,obj,functionCall,args);
        if (this._delayer == null) {
                this._delayer = setInterval(doDelayed, 10, this);
        }
}

function doDelayed(obj) {
        var curTime = new Date();
        if (functionArray !=null && functionArray.length > 0) {
                for (i=0; i<functionArray.length; i++) {
                        if (curTime.getTime() >= functionArray[i][0]) {
                                //Call the actual function!
                                functionArray[i][2].apply(null,functionArray[i][3]);

                                //it's been called, remove this one from the array!
                                functionArray.splice(i,1);
                        }
                }
        } else {
                trace("done");
                clearInterval(obj._delayer);
        }
}

